package data

import (
	"fmt"
	"gitchina/kly_service/util"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
)

type LogisticsCorpDto struct {
	Id        int    `orm:"pk;column(id)"`
	Name      string `orm:"column(name)"`
	Coord     string `orm:"column(coord)"`
	GeoHash   string `orm:"column(geo_hash)"`
	Addr      string `orm:"column(addr)"`
	AreaId    int    `orm:"column(area_id)"`
	Telephone string `orm:"column(telephone)"`
}

type LogisticsCorpGetDto struct {
	Name       string `orm:"column(name)"`
	CorpName   string `orm:"column(corp_name)"`
	CorpAddr   string `orm:"column(corp_addr)"`
	Telephone  string `orm:"column(telephone)"`
	Remark     string `orm:"column(remark)"`
	AreaId     int    `orm:"column(area_id)"`
	BizLicense string `orm:"column(biz_license)"`
	BizPermit  string `orm:"column(biz_permit)"`
}

type LogisticsCorpDetailDto struct {
	OwnerName  string `orm:"column(owner_name)"`
	OwnerPhone string `orm:"column(owner_phone)"`
	OwnerPhoto string `orm:"column(owner_photo)"`
	OwnerId    int    `orm:"column(owner_id)"`
	CorpName   string `orm:"column(corp_name)"`
	Intro      string `orm:"column(intro)"`
}

type LogisticsBizDto struct {
	Id          int    `orm:"pk;auto;column(id)"`
	Intro       string `orm:"column(intro)"`
	ServiceType int    `orm:"column(service_type)"`
	BizAddr     string `orm:"column(biz_addr)"`
}

type InvoiceCorpDto struct {
	Id     int    `orm:"pk;auto;column(id)"`
	Name   string `orm:"column(name)"`
	AreaId int    `orm:"column(area_id)"`
	Addr   string `orm:"column(addr)"`
}

type QueryLogisticsCorpListParam struct {
	StartArea int
	EndArea   int
	PageNo    int
	PageSize  int
}

func (c *LogisticsCorpDto) TableName() string {
	return "l_logistics"
}

func (c *InvoiceCorpDto) TableName() string {
	return "l_invoice_corp"
}

func (r LogisticsRepo) AddOrUpdateLogisticsCorp(empDto *LogisticsEmpDto, corpDto *LogisticsCorpDto) (id int64, err error) {
	var id32 int
	var list orm.ParamsList
	o := orm.NewOrm()
	num, err := o.Raw(SQL_Logis_Get_Corp_Exists, corpDto.Name).ValuesFlat(&list)
	if err == nil {
		if num == 0 {
			id, err = o.Insert(corpDto)
		} else {
			idStr := list[0].(string)
			if id32, err = strconv.Atoi(idStr); err == nil {
				corpDto.Id = id32
				id = int64(id32)
				o.Update(corpDto)
			}
		}

		if id != 0 {
			var repo MemberRepo
			empDto.CorpId = int(id)
			repo.UpdateEmp(empDto)
		}
	}

	return
}

func (l LogisticsRepo) GetLogisticsCorpList(areaId, pageNo, pageSize int) ([]LogisticsCorpDetailDto, int, error) {
	var err error
	var num int64
	var rowCount int
	var flat orm.ParamsList
	var list []LogisticsCorpDetailDto
	o := orm.NewOrm()
	if num, err = o.Raw(fmt.Sprintf(SQL_Logis_Get_Corp_List, (pageNo-1)*pageSize, pageSize), areaId).QueryRows(&list); num >= 1 {
		if num, err = o.Raw(fmt.Sprintf(SQL_Logis_Get_Corp_List_Count), areaId).ValuesFlat(&flat); num >= 1 {
			rowCount, err = strconv.Atoi(flat[0].(string))
			util.GetLogger().Debug("[data-GetLogisticsCorpList] - debug:rowcount::%s", flat[0])
		}
	}
	return list, rowCount, err
}

func (l LogisticsRepo) QueryLogisticsCorpList(areaId string, pageNo, pageSize int) ([]LogisticsCorpDetailDto, int, error) {
	var err error
	var num int64
	var rowCount int
	var flat orm.ParamsList
	var list []LogisticsCorpDetailDto
	o := orm.NewOrm()
	if num, err = o.Raw(fmt.Sprintf(SQL_Logis_Query_Corp_List, areaId+"%", (pageNo-1)*pageSize, pageSize)).QueryRows(&list); num >= 1 {
		if num, err = o.Raw(fmt.Sprintf(SQL_Logis_Query_Corp_List_Count, areaId+"%")).ValuesFlat(&flat); num >= 1 {
			rowCount, err = strconv.Atoi(flat[0].(string))
			util.GetLogger().Debug("[data-QueryLogisticsCorpList] - debug:rowcount::%s", flat[0])
		}
	}
	return list, rowCount, err
}

func (r LogisticsRepo) GetLogisticsCorpDetail(empId int) (dto LogisticsCorpDetailDto, err error) {
	o := orm.NewOrm()
	err = o.Raw(SQL_Logis_Get_Logistics_Corp_Detail, empId).QueryRow(&dto)
	return
}

func (r LogisticsRepo) UpdateLogisticsBiz(dto *LogisticsBizDto) error {
	o := orm.NewOrm()
	_, err := o.Raw(SQL_Logis_Update_Logistics_Biz, dto.Intro, dto.ServiceType, dto.BizAddr, dto.Id).Exec()
	return err
}

func (r LogisticsRepo) GetLogisticsBiz(id int) (dto LogisticsBizDto, err error) {
	o := orm.NewOrm()
	err = o.Raw(SQL_Logis_Get_Logistics_Biz, id).QueryRow(&dto)
	return
}

func (r LogisticsRepo) GetLogisticsCorp(memberId int) (dto LogisticsCorpGetDto, err error) {
	o := orm.NewOrm()
	err = o.Raw(SQL_Logis_Get_Logistics_Corp, memberId).QueryRow(&dto)
	return
}

func (l LogisticsRepo) GetInvoiceCorps() []InvoiceCorpDto {
	var list []InvoiceCorpDto
	o := orm.NewOrm()
	_, _ = o.Raw(SQL_Logis_Get_Invoice_Corps).QueryRows(&list)
	return list
}

// func (r LogisticsRepo) getQueryLogisticsCorpListCond(param QueryLogisticsCorpListParam) (string, []interface{}) {
// 	var buffer bytes.Buffer
// 	var args = make([]interface{}, 0)
// 	if param.StartArea != 0 {
// 		if param.StartArea%10000 == 0 {
// 			buffer.WriteString(" AND src_province = ?")
// 		} else {
// 			buffer.WriteString(" AND src_city = ?")
// 		}
// 		args = append(args, param.StartArea)
// 	}
// 	if param.EndArea != 0 {
// 		if param.EndArea%10000 == 0 {
// 			buffer.WriteString(" AND dest_province = ?")
// 		} else {
// 			buffer.WriteString(" AND dest_city = ?")
// 		}
// 		args = append(args, param.EndArea)
// 	}

// 	buffer.WriteString(fmt.Sprintf(" LIMIT %d, %d", (param.PageNo-1)*param.PageSize, param.PageSize))

// 	return buffer.String(), args
// }

func init() {
	orm.RegisterModel(new(LogisticsCorpDto), new(InvoiceCorpDto))
}
